#!/user/bin/env python3
# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# @Time:       2024/6/7 14:45
# Author:      003
# @File:       files.py
# @Python:     3.11
"""
"""
# -------------------------------------------------------------------------------
import os, sys
from flask import Flask, render_template, request, send_file, Blueprint, send_from_directory
import glob
# from app import app

# app = Flask(__name__)
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
index_page = Blueprint("file", __name__)
#region 文件列表

base_dir = './files'
# os.chdir('/flask')
@index_page.route('/download')
def filelist():

    pattern = '*.xlsx'
    # ;*.xls;*.doc;*.docx;*.txt;*.pdf;*.jpg;*.png;*.gif;*.zip;*.rar;*.7z;*.mp3;*.mp4;*.avi;*.mkv;*.flv;*.wmv;*.rmvb;*.mov;*.wav;*.3gp;*.asf;*.rm;*.rm
    files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]
    # os.chdir(MyFolder)
    # 这里做文件筛选
    maps = {}
    for fname in files:
        if os.path.isfile(fname):
            key = fname
            maps[key] = os.path.getsize(fname) // 1024

    return render_template('download.htm', files=maps)

#endregion

# @app.route("/")
# def index():
#     html = """<html>
#         <head>
#           <title>File Upload</title>
#         </head>
#         <body>
#             <form action="/upload" method="POST" enctype="multipart/form-data">
#                 <input type="file" name="file" multiple="multiple" />
#                 <input type="submit" value="提交" />
#             </form>
#         </body>
#         </html>"""
#     return html


@index_page.route("/upload", methods=["POST"])
def upload_file():
    try:
        # f = request.files["file"]

        for f in request.files.getlist('file'):
            filename = os.path.join(BASE_PATH, "upload", f.filename)
            print(filename)
            f.save(filename)
        return "file upload successfully!"
    except Exception as e:
        return "failed!"



@index_page.route("/files/<filename>", methods=["GET"])
def download_file(filename):
    dir = os.path.join(BASE_PATH, 'files')
    return send_from_directory(dir, filename, as_attachment=True)


def mkdir(dirname):
    dir = os.path.join(BASE_PATH, dirname)
    if not os.path.exists(dir):
        os.makedirs(dir)
